#include <iostream>
#include <fstream>
#include <cassert>
#include <vector>
#include <string>

#include "../util.h"

using std::cout;
using std::cerr;
using std::ifstream;
using std::vector;
using std::string;

void PrintUsage() {
    std::cerr << "Usage: check source_sentences translation_candidates choice\n";
}

int main(int argc, char **argv) {
    if (argc != 4) {
        PrintUsage();
        return 1;
    }

    string inputPhrasesFilename(argv[1]);
    string translationCandidatesFilename(argv[2]);
    string choicesFilename(argv[3]);

    vector<string> srcSentences;
    vector< vector< vector<string> > > targets;

    ifstream sourceIfstream(inputPhrasesFilename.c_str());
    string sentence;
    while (getline(sourceIfstream, sentence)) {
        srcSentences.push_back(sentence);
    }

    size_t sentenceCount = srcSentences.size();
    ifstream targetIfstream(translationCandidatesFilename.c_str());
    targets.resize(sentenceCount);

    string targetLine;
    while (getline(targetIfstream, targetLine)) {
        vector<string> tokens = SplitString(targetLine, " ||| ");
        assert(tokens.size() == 3);
        size_t sentenceNum = FromString<size_t>(tokens[0]);
        assert(sentenceNum < sentenceCount);
        string candidatePhrase = tokens[1];
        RTrim(candidatePhrase);
        targets[sentenceNum].push_back(SplitString(candidatePhrase));
    }

    ifstream choiceIfstream(choicesFilename.c_str());
    vector<string> choiceLines;
    string choiceLine;
    while (getline(choiceIfstream, choiceLine)) {
        choiceLines.push_back(choiceLine);
        if (choiceLines.size() > sentenceCount) {
            cerr << "Too many lines - there are only " << sentenceCount << " sentences in the input\n";
            return 1;
        }
    }
    if (choiceLines.size() < sentenceCount) {
        cerr << "Not enough lines - there are " << sentenceCount << " sentences in the input\n";
        return 1;
    }
    for (size_t i = 0; i < sentenceCount; ++i) {
        size_t res = FromString<size_t>(choiceLines[i]);
        if (res < targets[i].size()) {
            cout << JoinString(targets[i][res]) << '\n';
        } else {
            cerr << "Result index out of bounds: " << res << " for sentence #" << i + 1 << '\n';
            return 1;
        }
    }

    return 0;
}
